package com.pureut.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.system.domain.FileTree;
import com.pureut.system.domain.dto.FileTreeListDto;
import com.pureut.system.mapper.FileTreeMapper;
import com.pureut.system.service.FileTreeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName FileTreeServiceImpl
 * @Description: 设备维修文件树结构
 * @Author: try
 * @CreateDate: 2025/4/11 13:51	//创建时间
 * @UpdateUser: try
 * @UpdateDate: 2025/4/11 13:51	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
@Service
public class FileTreeServiceImpl extends ServiceImpl<FileTreeMapper, FileTree> implements FileTreeService
{

    @Resource
    FileTreeMapper fileTreeMapper;

    /**
     * 新增树结构
     * @param fileTree
     * @return
     */
    @Override
    public boolean add(FileTree fileTree)
    {
        return save(fileTree);
    }

    /**
     * 树结构
     */
    @Override
    public List<FileTreeListDto> getTree(FileTree fileTree)
    {
        //查询
        return selectTree(fileTree);
    }


    /**
     * 查询树形结构
     */
     List<FileTreeListDto> selectTree(FileTree fileTree) {
        // 查询所有节点
        List<FileTreeListDto> allNodes = fileTreeMapper.getList(fileTree);

        // 构建树形结构
        return buildTree(allNodes);
    }

    public List<FileTreeListDto> buildTree(List<FileTreeListDto> allNodes) {
        List<FileTreeListDto> roots = new ArrayList<>();
        for (FileTreeListDto node : allNodes) {
            if (node.getParentId().equals("0")) { // 根节点判断
                roots.add(findChildren(node, allNodes));
            }
        }
        return roots;
    }



    private FileTreeListDto findChildren(FileTreeListDto parent, List<FileTreeListDto> allNodes) {
        List<FileTreeListDto> children = allNodes.stream()
                .filter(node -> String.valueOf(parent.getId()).equals(node.getParentId()))
                .map(node -> findChildren(node, allNodes))
                .collect(Collectors.toList());
        parent.setChildren(children);
        return parent;
    }

    /**
     * 文件类型下拉
     * @param fileTree
     * @return
     */
    @Override
    public List<FileTree> getFileType(FileTree fileTree)
    {
        List<FileTree> fileTrees = fileTreeMapper.selectList(new QueryWrapper<FileTree>().lambda()
                .eq(FileTree::getParentId, "0"));
        return fileTrees;
    }
}